<script setup>
import LineChart from '../components/lineChart.vue'
import ModelAnalysis from '../components/ModelAnalysis.vue'
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import infImg1 from '@/views/Big/images/inferenceSample/1.jpg'
import infImg2 from '@/views/Big/images/inferenceSample/2.jpg'
import infImg3 from '@/views/Big/images/inferenceSample/3.jpg'
import infImg4 from '@/views/Big/images/inferenceSample/4.jpg'
import infImg5 from '@/views/Big/images/inferenceSample/5.jpg'
import infImg6 from '@/views/Big/images/inferenceSample/6.jpg'
import { ElImage } from 'element-plus'
import { useInference } from '@/composables/useInference'
import emitter from '@/utils/eventBus'

const { getTaskProgress } = useInference()

// 复用 TrainingLog 的逻辑
const evolutionLogs = ref([])

const updateEvolutionLog = (log, isHighlight = false) => {
  evolutionLogs.value.push({
    id: Date.now(),
    content: log,
    isHighlight,
    timestamp: new Date().toLocaleTimeString()
  })
  
  if (evolutionLogs.value.length > 100) {
    evolutionLogs.value.shift()
  }

  nextTick(() => {
    const logContent = document.querySelector('.log-content')
    if (logContent) {
      logContent.scrollTop = logContent.scrollHeight
    }
  })
}

// 修改生成日志的逻辑
const generateTaskSpecificLogs = (taskType) => {
  switch(taskType) {
    case 'upload':
      return [
        { content: '边侧难辨别样本归集...', delay: 1000 },
        { content: '边侧难辨别样本归集完成', delay: 2500 },
        { content: '样本上传中...', delay: 4000 }
      ];
    case 'start':
      return [
        { content: '边侧归集样本数据集构建...', delay: 1000 },
        { content: '加载历史模型参数...', delay: 2000 },
        { content: '开始增量学习...', delay: 3000 }
      ];
    case 'evolution':
      return [
        { content: '云侧增量模型加载参数...', delay: 1000 },
        { content: '省侧历史模型加载参数...', delay: 2000 }
      ];
    case 'assessment':
      return [
        { content: '开启模型评估...', delay: 1000 },
        { content: '加载增量数据...', delay: 2000 },
        { content: '加载历史数据...', delay: 3000 },
        { content: '模型性能评估....', delay: 4000 },
        { content: '模型遗忘指数评估...', delay: 5000 },
        { content: '模型性能评估结果acc: 89%', delay: 6000 },
        { content: '模型遗忘指数: 4%', delay: 7000 }
      ];
    case 'issued':
      return [
        { content: '模型轻量化（量化）中...', delay: 1000 },
        { content: '边侧选择更新模型ID', delay: 3000 },
        { content: '云边参数同步...', delay: 5000 }
      ];
    default:
      return [];
  }
};

// 添加任务类型状态
const currentTask = ref(null);

// 修改 props 以接收当前任务类型
const props = defineProps({
  taskType: String
});

// 修改 watch 以响应任务类型变化和性能数据更新
watch(() => props.taskType, (newTaskType) => {
  if (newTaskType) {
    currentTask.value = newTaskType;
  }
}, { immediate: true });

// 添加启动日志的方法
const startTaskLogs = () => {
  evolutionLogs.value = []; // 清空之前的日志
  const logs = generateTaskSpecificLogs(currentTask.value);
  
  // 按照指定延迟依次显示日志
  logs.forEach((log, index) => {
    setTimeout(() => {
      updateEvolutionLog(log.content, true);
    }, log.delay);
  });

  // 如果是增量学习或协同进化任务，需要持续更新性能数据
  if (currentTask.value === 'start' || currentTask.value === 'evolution') {
    startPerformanceUpdates();
  }
};

// 暴露方法给父组件
defineExpose({
  startTaskLogs
});

// 在文件顶部的其他 ref 定义附近添加
const logInterval = ref(null);

// 修改性能数据更新逻辑
const startPerformanceUpdates = () => {
  // 先清理已存在的定时器
  if (logInterval.value) {
    clearInterval(logInterval.value);
  }

  // 不再需要在这里直接更新日志，因为会通过事件总线接收更新
  const updateInterval = setInterval(async () => {
    try {
      await getTaskProgress('latest')
      // 性能数据的更新和日志显示会通过事件总线处理
    } catch (error) {
      console.error('获取性能数据失败:', error)
    }
  }, 4000);

  logInterval.value = updateInterval;
};

// 修改 onUnmounted 确保清理所有定时器
onUnmounted(() => {
  if (logInterval.value) {
    clearInterval(logInterval.value);
    logInterval.value = null;
  }
  currentTask.value = null;
  
  // 移除事件监听
  emitter.off('performance-update');
});

// 添加预览图片数组
const previewInferenceImages = ref([])
const loadPreviewInferenceImages = () => {
  previewInferenceImages.value = [infImg1, infImg2, infImg3, infImg4, infImg5, infImg6]
}

onMounted(() => {
  updateEvolutionLog('协同进化系统启动', true)
  updateEvolutionLog('初始化边缘设备连接...', false)
  loadPreviewInferenceImages()

  // 修改性能数据更新的事件监听
  emitter.on('performance-update', (data) => {
    // 只在数据有效时才更新日志
    if (data.accuracy > 0 && data.loss > 0) {
      if (currentTask.value === 'start') {
        updateEvolutionLog(
          `当前训练精度: ${data.accuracy.toFixed(2)}%, 损失值: ${data.loss.toFixed(3)}`,
          false
        )
      } else if (currentTask.value === 'evolution') {
        updateEvolutionLog(`云边模型输出logits同步`, false)
        updateEvolutionLog(`省侧模型性能: ${data.accuracy.toFixed(2)}%`, true)
      }
    }
  })
})
</script>

<template>
  <div class="bottom-container">
    <div class="evolution-display-container">
      <div class="title">
        <span>协同进化任务日志显示</span>
      </div>
      <div class="log-content">
        <div
          v-for="log in evolutionLogs"
          :key="log.id"
          :class="['log-item', { 'highlight': log.isHighlight }]"
        >
          <span class="log-time">{{ log.timestamp }}</span>
          <span class="log-text">{{ log.content }}</span>
        </div>
      </div>
    </div>
    <div class="evolution-display-container" style="width: 45%">
      <div class="title">
        <span>进化模型遗忘与性能分析</span>
      </div>
      <ModelAnalysis />
    </div>
    <div class="evolution-display-container">
      <div class="title">
        <span>推理样本展示</span>
      </div>
      <div class="inference-preview-container">
        <div class="image-preview-container">
          <div v-for="(img, index) in previewInferenceImages" 
               :key="index" 
               class="preview-item">
            <el-image 
              :src="img" 
              :preview-src-list="previewInferenceImages"
              :initial-index="index"
              fit="cover"
              class="preview-image"
              preview-teleported
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.bottom-container {
  width: 100%;
  height: 35%;
  position: absolute;
  // bottom: 5%;
  top: 70%;
  left: 0;
  display: flex;
  justify-content: space-between;

  .evolution-display-container {
    width: 25.5%;
    height: 100%;
    padding: 10px;
    position: relative;
    border-radius: 10px;
    background: linear-gradient(135deg, rgba(62, 172, 180, 0.05) 0%, rgba(9, 196, 202, 0.1) 100%);
    backdrop-filter: blur(5px);
    border: 1px solid rgba(62, 172, 180, 0.2);
    box-shadow:
      0 0 20px rgba(62, 172, 180, 0.1),
      inset 0 0 20px rgba(62, 172, 180, 0.05);

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 1px;
      background: linear-gradient(90deg, transparent, rgba(62, 172, 180, 0.3), transparent);
    }
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 1px;
      background: linear-gradient(90deg, transparent, rgba(62, 172, 180, 0.3), transparent);
    }

    .title {
      width: 100%;
      height: 10%;
      background: url(../images/title.png) no-repeat center;
      background-size: 100%;
      color: #fff;
      text-align: center;
      display: table;
      font-size: 0.9rem;

      span {
        display: table-cell;
        vertical-align: middle;
      }
    }
  }

  .log-content {
    height: calc(90% - 10px);
    overflow-y: auto;
    padding: 8px;
    display: flex;
    flex-direction: column;
    scroll-behavior: smooth;
    
    &::-webkit-scrollbar {
      width: 4px;
    }
    
    &::-webkit-scrollbar-track {
      background: rgba(62, 172, 180, 0.1);
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: rgba(62, 172, 180, 0.3);
      border-radius: 3px;
      
      &:hover {
        background: rgba(62, 172, 180, 0.5);
      }
    }
  }

  .log-item {
    margin-bottom: 6px;
    padding: 4px 8px;
    font-size: 0.6rem;
    background: rgba(40, 44, 52, 0.3);
    border-radius: 4px;
    line-height: 1.3;
    color: #fff;
    transition: all 0.3s ease;
    border-left: 2px solid rgba(62, 172, 180, 0.3);
    word-break: break-word;
    white-space: pre-wrap;
    flex-shrink: 0;
    
    &.highlight {
      background: rgba(242, 151, 1, 0.08);
      border-left: 2px solid rgba(242, 151, 1, 0.6);
      animation: glow 1.5s infinite alternate;
    }

    .log-time {
      color: #65959b;
      margin-right: 8px;
      font-size: 0.55rem;
      font-family: var(--font-family-mono);
    }

    .log-text {
      color: #a8c1c3;
      font-family: var(--font-family-mono);
    }
  }

  .inference-preview-container {
    width: 100%;
    margin-top: -10px;
    padding: 10px;

    .image-preview-container {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 10px;
      margin-top: 5px;
      padding: 5px;
      height: calc(100% - 10px);
    }

    .preview-item {
      aspect-ratio: 1;
      border-radius: 4px;
      overflow: hidden;
      cursor: pointer;
      border: 1px solid rgba(62, 172, 180, 0.3);
      transition: all 0.3s ease;
      height: 80px;

      &:hover {
        transform: scale(1.05);
        border-color: #f29701;
        box-shadow: 0 0 10px rgba(242, 151, 1, 0.3);
      }
    }

    :deep(.el-image) {
      width: 100%;
      height: 100%;
      
      .el-image__inner {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}

@keyframes glow {
  from {
    box-shadow: 0 0 3px rgba(242, 151, 1, 0.15);
  }
  to {
    box-shadow: 0 0 6px rgba(242, 151, 1, 0.3);
  }
}
</style>
